package com.jkoss.wine.system.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.CryptoUtils;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.common.vo.ZtreeBean;
import com.jkoss.wine.system.entity.MerchantEmployees;
import com.jkoss.wine.system.entity.MerchantEmployeesRole;
import com.jkoss.wine.system.entity.Permission;
import com.jkoss.wine.system.entity.Role;
import com.jkoss.wine.system.mapper.MerchantEmployeesMapper;
import com.jkoss.wine.system.service.IDepartmentService;
import com.jkoss.wine.system.service.IMerchantEmployeesRoleService;
import com.jkoss.wine.system.service.IMerchantEmployeesService;
import com.jkoss.wine.system.service.IRoleService;

/**
 * 
 * 
 * @Author chair
 * @Version 1.0, 2018年9月23日
 * @See
 * @Since com.jkoss.mengal.system.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/system/merchantEmployees")
public class MerchantEmployeesController extends BaseController {

	@Autowired
	private IMerchantEmployeesService iMerchantEmployeesService;
	@Autowired
	private IRoleService iRoleService;
	@Autowired
	private IMerchantEmployeesRoleService iMerchantEmployeesRoleService;
	@Autowired
	private IDepartmentService iDepartmentService;

	/**
	 * 列表
	 * 
	 * @param dwzPageBean
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/list")
	@RequiresPermissions("/system/merchantEmployees/list")
	public String list(String employeeName, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		dwzPageBean.getCountResultMap().put("employeeName", employeeName);
		Wrapper wrapper = Condition.create().ne("me.del", 1).like("me.employee_name", employeeName);

		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("me.add_time", false);
		}

		Page resultPage = iMerchantEmployeesService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "system/merchantEmployees/list";
	}

	/**
	 * 去添加
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toInsert")
	@RequiresPermissions("/system/merchantEmployees/toInsert")
	public String toInsert(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Wrapper dwrapper = Condition.create().ne("del", 1);
		List list = iDepartmentService.selectList(dwrapper);
		map.put("departments", list);

		// 构建排序条件
		Wrapper wrapper = Condition.create().ne("del", 1).orderBy("pid", true);
		List<Role> roles = iRoleService.selectList(wrapper);
		// 把查询回来的实体转成ZtreeBean
		if (!CommonUtil.isBlank(roles)) {
			List<ZtreeBean> ztreeBeans = new ArrayList();
			for (Role role : roles) {
				ZtreeBean ztreeBean = new ZtreeBean();
				ztreeBean.setId(role.getId() + "");
				ztreeBean.setIsParent(CommonUtil.isBlank(role.getPid()));
				ztreeBean.setName(role.getName());
				ztreeBean.setPId(role.getPid());
				ztreeBean.setOpen(true);
				ztreeBeans.add(ztreeBean);
			}
			map.put("ztreeBeans", JSON.toJSONString(ztreeBeans));
		} else {
			map.put("ztreeBeans", "[]");
		}

		return "system/merchantEmployees/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/system/merchantEmployees/toInsert")
	@ResponseBody
	public Object insert(@Valid MerchantEmployees merchant_employees, String[] rid, HttpServletRequest request, HttpServletResponse response) {

		// 判断用户是否存在
		Wrapper wrapper = Condition.create().eq("account_num", merchant_employees.getAccountNum());
		MerchantEmployees employees = iMerchantEmployeesService.selectOne(wrapper);
		if (!CommonUtil.isBlank(employees)) {
			return ajaxError("用户已存在");
		}
		// 判断手机号码是否存在
		Wrapper wrapper1 = Condition.create().eq("employee_phone", merchant_employees.getEmployeePhone());
		MerchantEmployees employees1 = iMerchantEmployeesService.selectOne(wrapper1);
		if (!CommonUtil.isBlank(employees1)) {
			return ajaxError("电话已存在");
		}
		// 添加时间
		merchant_employees.setAddTime(CommonUtil.getDate());
		// 操作人
		// merchant_employees.setOperator(operator);
		// 密碼
		merchant_employees.setAccountPwd(CryptoUtils.encodeMD5("88888888"));
		// 是否删除 0否1是
		merchant_employees.setDel(0);

		if (iMerchantEmployeesService.insertMerchantEmployees(merchant_employees, rid)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	/**
	 * 去修改
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUpdate")
	@RequiresPermissions("/system/merchantEmployees/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		map.put("record", iMerchantEmployeesService.selectById(id));

		Wrapper dwrapper = Condition.create().ne("del", 1);
		List list = iDepartmentService.selectList(dwrapper);
		map.put("departments", list);

		// 查询该角色得权限
		List<String> rids = iMerchantEmployeesRoleService.selectRidByMeid(id);
		// 构建排序条件
		Wrapper wrapper = Condition.create().ne("del", 1).orderBy("pid", true);
		List<Role> roles = iRoleService.selectList(wrapper);
		// 把查询回来的实体转成ZtreeBean
		if (!CommonUtil.isBlank(roles)) {
			List<ZtreeBean> ztreeBeans = new ArrayList();
			for (Role role : roles) {
				ZtreeBean ztreeBean = new ZtreeBean();
				ztreeBean.setId(role.getId() + "");
				ztreeBean.setIsParent(CommonUtil.isBlank(role.getPid()));
				ztreeBean.setName(role.getName());
				ztreeBean.setPId(role.getPid());
				ztreeBean.setOpen(true);
				// 匹配该权限是否已经选中
				ztreeBean.setChecked(rids.contains(role.getId()));
				ztreeBeans.add(ztreeBean);
			}
			map.put("ztreeBeans", JSON.toJSONString(ztreeBeans));
		} else {
			map.put("ztreeBeans", "[]");
		}

		return "system/merchantEmployees/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/system/merchantEmployees/toUpdate")
	@ResponseBody
	public Object update(@Valid MerchantEmployees merchant_employees, String[] rid, HttpServletRequest request, HttpServletResponse response) {
		// 不能修改用户名
		merchant_employees.setAccountNum(null);
		if (iMerchantEmployeesService.updateMerchantEmployees(merchant_employees, rid)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去删除
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("/system/merchantEmployees/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		List list = new ArrayList();
		for (String string : id) {
			MerchantEmployees merchantEmployees = new MerchantEmployees();
			merchantEmployees.setEmployeeId(string);
			// 是否删除：0-未删除、1-已删除、2-不能删除
			merchantEmployees.setDel(1);
			list.add(merchantEmployees);
		}
		if (iMerchantEmployeesService.updateBatchById(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去修改角色
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUpdateRole")
	@RequiresPermissions("/system/merchantEmployees/toUpdateRole")
	public String toUpdateRole(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {

		// 找到所有角色
		map.put("roles", iRoleService.selectList(Condition.create().ne("del", 1)));
		// 传递到前端
		map.put("id", id);
		Wrapper wrapper = Condition.create().eq("meid", id);
		List<MerchantEmployeesRole> merchantEmployeesRole = iMerchantEmployeesRoleService.selectList(wrapper);
		if (!CommonUtil.isBlank(merchantEmployeesRole)) {
			String rid = "";
			for (MerchantEmployeesRole merchantEmployeesRole2 : merchantEmployeesRole) {
				rid += merchantEmployeesRole2.getRid() + ",";
			}
			map.put("rid", rid);
		}
		return "system/merchantEmployees/updateRole";
	}

	@RequestMapping("/updateRole")
	@RequiresPermissions("/system/merchantEmployees/toUpdateRole")
	@ResponseBody
	public Object updateRole(String id, String[] rid, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		if (iMerchantEmployeesRoleService.updateRole(id, rid)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去修改密码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toChangePassword")
	public String toChangePassword() {
		return "system/merchantEmployees/changePassword";
	}

	/**
	 * 修改密码
	 * 
	 * @param oldPwd
	 *            旧密码
	 * @param pwd
	 *            新密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/changePassword")
	@ResponseBody
	public Object changePassword(String oldPwd, String pwd, HttpServletRequest request, HttpServletResponse response) {
		MerchantEmployees merchant_employees = iMerchantEmployeesService.selectById(getUserId());
		if (CommonUtil.isEquals(CryptoUtils.encodeMD5(oldPwd), merchant_employees.getAccountPwd())) {
			merchant_employees.setAccountPwd(CryptoUtils.encodeMD5(pwd));
		} else {
			return ajaxError("请输入正确的旧密码");
		}
		if (iMerchantEmployeesService.updateById(merchant_employees)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去修改个人信息
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toChangeInfo")
	public String toChangeInfo(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		map.put("record", iMerchantEmployeesService.selectById(getUserId()));
		return "system/merchantEmployees/changeInfo";
	}

	@RequestMapping("/changeInfo")
	@ResponseBody
	public Object changeInfo(@Valid MerchantEmployees merchant_employees, HttpServletRequest request, HttpServletResponse response) {
		// 不能修改用户名
		merchant_employees.setAccountNum(null);
		if (iMerchantEmployeesService.updateById(merchant_employees)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}
}
